<template>
  <div>
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体部分 -->
    <el-card>
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索栏 -->
          <el-input
            placeholder="请输入内容"
            v-model="userInfo.query"
            clearable
            @clear="getUserList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button> </el-input
        ></el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户表格区域 -->
      <el-table :data="userlist" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              effect="dark"
              content="修改角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 弹出创建用户对话框 -->
      <el-dialog
        title="创建用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 主体部分 -->
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 弹出修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          :rules="editUserFormrRules"
          ref="editUserFormrRef"
          :model="editUserForm"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 弹出分配用户对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        close="setRoleDialogClose"
      >
        <div>
          <p>当前的用户:{{ this.userInfo.username }}</p>
          <p>当前的角色:{{ this.userInfo.role_name }}</p>
          <p>
            分配新角色:
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolelist"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
name:'',
  data() {
    //验证邮箱规则
    const checkEmail=(rule, value, callback)=>{
      const regEmail=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if(regEmail.test(value)){
        return callback();
      }else{
        return callback(new Error('请输入正确的邮箱'));
      };
    };
    //验证手机号码规则
    const checkMobile=(rule, value, callback)=>{
      const regEmail=/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if(regEmail.test(value)){
        return callback();
      }else{
        return callback(new Error('请输入正确的手机号'));
      };
    };
    return {
      userInfo:{
        query:'',
        //当前页数
        pagenum:1,
        //当前页的数据量
        pagesize:2,
      },
      //被选中的用户信息
      userlist:{},
      //所有角色的信息
      rolelist:[],
      //被选中的角色的id
      selectedRoleId:'',
      //总共数据量
      total:''-0,
      //是否显示创建用户对话框
      addDialogVisible:false,
      //是否显示修改用户对话框
      editDialogVisible:false,
      //是否显示分配用户对话框
      setRoleDialogVisible:false,
      //创建用户信息
      addUserForm:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
      //修改用户信息
      editUserForm:{

      },
      //创建用户信息规则
      addUserFormRules:{
          username: [
             { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '用户名长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password: [
             { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
          ],
          email: [
             { required: true, message: '请输入邮箱', trigger: 'blur' },
             { validator: checkEmail, trigger: 'blur' }
          ],
          mobile: [
             { required: true, message: '请输入手机', trigger: 'blur' },       
             { validator: checkMobile, trigger: 'blur' }
          ],
      },
      //修改用户信息规则
      editUserFormrRules:{
          email: [
             { required: true, message: '请输入邮箱', trigger: 'blur' },
             { validator: checkEmail, trigger: 'blur' }
          ],
          mobile: [
             { required: true, message: '请输入手机', trigger: 'blur' },       
             { validator: checkMobile, trigger: 'blur' }
          ],
      }
      
    }
  },
  created(){
    this.getUserList();
  },
  components: {

  },
  methods:{
    //获取用户列表信息
    async getUserList(){
      const {data:res}=await this.$http.get('users',{params:this.userInfo});
      if(res.meta.status!==200) return this.$message.error('获取用户信息失败');
      this.userlist=res.data.users;
      this.total=res.data.total;
    },
    handleSizeChange(N){
      console.log(N);
    },
    //当前页数的改变
    handleCurrentChange(newPageNum){
      this.userInfo.pagenum=newPageNum;
      //重新发送请求
      this.getUserList();
    },
    //当前页数据量的改变
    handleSizeChange(newPagesize){
      this.userInfo.pagesize=newPagesize;
      //重新发送请求
      this.getUserList();
    },
    //关于用户状态的修改
    async userStateChange(userInfo){
      console.log(userInfo);
      const {data:res}=await this.$http.put('users/'+userInfo.id+'/state/'+userInfo.mg_state);
      if(res.meta.status!=200){
        userInfo.mg_state=!userInfo.mg_state;
        return this.$message.error('更新用户状态失败');
      }
      this.$message({
          showClose: true,
          message: '更新用户状态成功',
          type: 'success'
      });
    },
    //关闭创建用户的弹出框时触发
    addDialogClose(){
      this.$refs.addUserFormRef.resetFields();
    },
    //点击确认后
    addUser(){
      this.$refs['addUserFormRef'].validate(async (valid) => {
        if (valid) {
          //发送请求
          const {data:res}= await this.$http.post('users',this.addUserForm);
          //创建失败
          if(res.meta.status!=201) return this.$message.error('创建用户失败');
          //创建成功
          this.$message({
          showClose: true,
          message: '创建用户成功',
          type: 'success'
          });
          //关闭对话框
          this.addDialogVisible = false;
          //重新获取列表数据
          this.getUserList();
        } else {
          return false
        }
      })
    },
    //修改用户
    async showEditDialog(id){
      const {data:res}=await this.$http.get('users/'+id);
      if(res.meta.status!=200) return this.$message.error('修改用户失败');
      this.editUserForm=res.data;
      //打开修改用户的弹出窗
      this.editDialogVisible=true;

    },
    //修改用户未提交清空数据
    editDialogClose(){
      this.$refs.editUserFormrRef.resetFields();
    },
    //点击确认修改用户信息
    editUserInfo(){
      this.$refs.editUserFormrRef.validate(async valid=>{
        if(valid){
          const {data:res}=await this.$http.put('users/'+this.editUserForm.id,{
            email:this.editUserForm.email,
            mobile:this.editUserForm.mobile,
          });
          if(res.meta.status!=200) return this.$message.error('修改用户失败');
          
          //重新获取数据
          this.getUserList()
          //弹出修改正确信息
          this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success'
          });
          //关闭对话框
          this.editDialogVisible = false
        }else{
          return
        }})
      
    },
    //删除用户
    async deleteUserById(id){
      const result=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          //删除失败
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        //删除成功
        if(result=='confirm'){
          const {data:res}=await this.$http.delete('users/'+id);
          if(res.meta.status!=200) return this.$message.error('删除失败！');
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getUserList();
        }
    },
    //分配用户
    async setRole(userlist){
      //被选中的用户信息
      this.userlist=userlist;
      const {data:res}=await this.$http.get('/roles');
      if(res.meta.status!=200) return this.$message.error('分配用户失败');
      //所有角色的信息
      this.rolelist=res.data;
      //弹出修改正确信息
      this.$message({
      showClose: true,
      message: '分配成功',
      type: 'success'
      });
      //打开页面
      this.setRoleDialogVisible=true;
    },
    //确认分配用户
    async setRoleInfo(){
      //没有被选中
      if(!this.selectedRoleId) return this.$message.error('请先分配用户');
      
      const {data:res}=await this.$http.put(`users/${this.userlist.id}/role`,{rid:this.selectedRoleId});
      if(res.meta.status!==200) return this.$message.error('分配用户失败');
      //弹出修改正确信息
      this.$message({
      showClose: true,
      message: '分配成功',
      type: 'success'
      });
      this.getUserList();
      //关闭页面
      this.setRoleDialogVisible=false;
      
    },
    setRoleDialogClose(){
      this.selectedRoleId='';
      this.userlist={};
    }
  }
}
</script>

<style lang="less" scoped>
</style>
